package net.israfil.markup.core;

import java.net.URL;

import net.israfil.markup.plugin.GUI;
import net.israfil.markup.plugin.Plugin;

import org.apache.tapestry.ioc.IOCUtilities;
import org.apache.tapestry.ioc.Registry;

public class MarkupApplication {
	
	private static MarkupApplication APP;	
	public static MarkupApplication getInstance() { return APP; }
	
	public static String MARKUP_MODEL_PACKAGE = "net.israfil.markup.model";
	public static String MARKUP_FILE_EXTENSION = "markup.xml";
	
	private Registry registry;
	
	private GUI gui;	
	
	public static void main(String ... args) {
		
		APP = new MarkupApplication(args[1]);

	}
	
	public MarkupApplication(String name) {
		registry = IOCUtilities.buildDefaultRegistry();		
		Plugin plugin = registry.getService(Plugin.class);
		URL definitionFile = Thread.currentThread().getContextClassLoader()
			.getResource(name+"."+MARKUP_FILE_EXTENSION);
		if (definitionFile == null)
			throw new IllegalArgumentException("No definition file found: " + name+"."+MARKUP_FILE_EXTENSION);
		gui = plugin.buildGUI(definitionFile);
	}
	
	public void start() {
		gui.start();
		while (gui.isRunning()) {
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				break;
			}
		}
	}
	
	public void stop() {
		try {
			gui.stop();
		} catch (InterruptedException e) {}
	}
	
	public Registry getRegistry() {
		return registry;
	}
	
	public <T> T getService(Class<T> serviceInterface) {
		return registry.getService(serviceInterface);
	}
	
	public <T> T getService(String serviceId, Class<T> serviceInterface) {
		return registry.getService(serviceId, serviceInterface);
	}
}
